package com.socialsoftware.repository;

import android.app.Application;

import androidx.lifecycle.LiveData;

import com.socialsoftware.model.AppDatabase;
import com.socialsoftware.model.User;
import com.socialsoftware.model.UserDao;

import java.util.List;

/**
 * Repository class that abstracts access to different data sources for User entities.
 * This provides a clean API for the ViewModel to interact with data.
 */
public class UserRepository {
    
    private UserDao userDao;
    private LiveData<List<User>> allUsers;
    
    public UserRepository(Application application) {
        AppDatabase db = AppDatabase.getDatabase(application);
        userDao = db.userDao();
        allUsers = userDao.getAllUsers();
    }
    
    // Room executes all queries on a separate thread.
    // Observed LiveData will notify the observer when the data has changed.
    public LiveData<List<User>> getAllUsers() {
        return allUsers;
    }
    
    public LiveData<User> getUserById(String id) {
        return userDao.getUserById(id);
    }
    
    public LiveData<User> getUserByUsername(String username) {
        return userDao.getUserByUsername(username);
    }
    
    // You must call these methods on a non-UI thread or your app will throw an exception.
    // Room ensures that you don't do any long-running operations on the main thread.
    public void insert(User user) {
        AppDatabase.databaseWriteExecutor.execute(() -> {
            userDao.insert(user);
        });
    }
    
    public void update(User user) {
        AppDatabase.databaseWriteExecutor.execute(() -> {
            userDao.update(user);
        });
    }
    
    public void delete(User user) {
        AppDatabase.databaseWriteExecutor.execute(() -> {
            userDao.delete(user);
        });
    }
    
    /**
     * Method to simulate fetching user data from a remote server
     * In a real app, this would make an API call to fetch user data
     * @param userId The ID of the user to fetch
     * @return A LiveData object containing the user data
     */
    public LiveData<User> fetchUserFromRemote(String userId) {
        // In a real app, this would make an API call
        // For now, we just return the local data
        return getUserById(userId);
    }
} 